package com.baizhi.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baizhi.entity.CmfzGuru;
import com.baizhi.service.CmfzGuruService;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("guru")
public class CmfzGuruController {
    @Autowired
    private CmfzGuruService cmfzGuruService;

    @RequestMapping("seletAll")
    @ResponseBody
    public List<CmfzGuru> seletAll(){
        return cmfzGuruService.selectAllGuru();
    }

    @RequestMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
//        1.获取 Excel文件对象
        List<CmfzGuru> cmfzGurus = cmfzGuruService.selectAllGuru();
        ExportParams exportParams = new ExportParams("所有的上师数据", "gurus");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, CmfzGuru.class, cmfzGurus);

//        2.设置响应头
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("guru.xlsx", "utf-8"));
        response.setContentType("application/vnd.ms-excel");

//        3.通过文件对象写出
        workbook.write(response.getOutputStream());
    }

    /**
     * 文件上传
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("importExcel")
    public void importExcel(MultipartFile file) throws Exception {
//        1.从file对象中获取流
        InputStream inputStream = file.getInputStream();

//        2.通过easypoi处理流
        ImportParams importParams = new ImportParams();
        importParams.setHeadRows(1);
        importParams.setTitleRows(1);

        List<CmfzGuru> cmfzGurus = ExcelImportUtil.importExcel(inputStream, CmfzGuru.class, importParams);

//        3.添加数据库
        for (CmfzGuru gurus : cmfzGurus) {
            System.out.println(gurus);
        }
    }
}
